#include "StdAfx.h"

#include <limits>



#include "MathUtils/Ray.h"
#include "ColorUtils/Color.h"
#include "ColorUtils/Image.h"
#include "FirstIntersectionResult.h"
#include "SecondIntersectionResult.h"
#include "Intersectable.h"
#include "Light.h"
#include "Scene.h"
#include "World.h"

#include "GreedyWorld.h"

void GreedyWorld::Init(Scene_ptr scene)
{
	_scene = scene;
}

void GreedyWorld::WhereIntersects(const Ray& ray, FirstIntersectionResult& result)
{
	SecondIntersectionResult tempResult;

	result.Set(NULL);

	for (std::vector<Intersectable_ptr>::iterator iter = _scene->Objects->begin(); iter != _scene->Objects->end(); iter++)
	{
		(*iter)->WhereIntersects(ray, tempResult);
		if (tempResult.Distance > 0.000001 && tempResult.Distance < result.Distance)	
			result = tempResult;
	}
}

void GreedyWorld::ColorAtIntersection(SecondIntersectionResult& result, const Point& /*point*/, const Ray& ray)
{
	if (result.Obj == NULL)
		if (_scene->ImageData.use_count() == 0 || result.isReflacted)
			result.ColorAtPoint = _scene->BackGroundColor;
		else
			result.ColorAtPoint = _scene->ImageData->GetColor(
				((double)(result.X + result.Width / 2) /  result.Width) * _scene->ImageData->Width(),
				((double)(result.Y + result.Height / 2) /  result.Height)* _scene->ImageData->Height());
	else
		result.Obj->ColorAtIntersection(result, ray.Shoot(result.Distance), ray);
}

Direction GreedyWorld::NormalAtPoint(FirstIntersectionResult&, const Point&)
{
	return Direction(-1, -1, -1);
}

GreedyWorld::~GreedyWorld() {}
